package com.zzh.controller;

import com.alibaba.fastjson.JSON;
import com.zjiecode.wxpusher.client.WxPusher;
import com.zjiecode.wxpusher.client.bean.Message;
import com.zjiecode.wxpusher.client.bean.MessageResult;
import com.zjiecode.wxpusher.client.bean.Result;
import com.zzh.bean.JsonRootBean;
import com.zzh.bean.Shop;
import com.zzh.bean.ShopInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.*;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;

/**
 * @author YYS
 * @version 1.0
 * @description:
 * @date 2023/5/10 下午4:50
 */
@Slf4j
@Component
public class SendShopTask {

    //用户token
    public static final String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiJ9.eyJleHAiOjE2ODQ5MTc3MDIsInVzZXJJZCI6NTI4Mjc3MzU4OTkzMDA3NSwiaWF0IjoxNjgzNzA4MTAyfQ.afwcxvsrLNbyH3WewboRLgd3fOnyP_DF4X3ZcGQqcsHFm1xzDtQyC4KBW3xRHrqeRm6wItxBh0hYS3KQIuthzw";
//    public static HashSet Uid =new HashSet<String>();
//    {
//        Uid.add("UID_m5uD0uGFMU23QfkIerfk3Tmt1Rk7");
//        Uid.add("UID_dGlfOwmFIxIIL7U6xjJgyjZG4yNw");
//    }

    @Scheduled(cron = "0/10 * * * * ? ")
    public void getShopCount() {
        if (CaCheUidUtils.getUid().size() <= 0) {
            log.info(" UID is null ");
            return;
        }
        HashMap<Long, String> dataMap = new HashMap<>();
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        //5 / 6 / 7 不同种类
        for (int i = 5; i < 8; i++) {
            //1-51 页数
            for (int j = 1; j < 5; j++) {
                String jsonData = "{\"page\":" + j + ",\"size\":20,\"resourceId\":" + i + ",\"orderBy\":\"SORT_DESC\"}";
                try {
                    HttpClient client = new HttpClient();
                    PostMethod postMethod = new PostMethod("https://mall-api.xwindlab.com/goods/queryGoodsListByDisplayResource");
                    postMethod.addRequestHeader("Content-type", "application/json; charset=utf-8");
                    postMethod.addRequestHeader("Authorization", token);
                    byte[] requestBytes = jsonData.getBytes("utf-8");

                    InputStream inputStream = new ByteArrayInputStream(requestBytes, 0, requestBytes.length);
                    // 请求体
                    RequestEntity requestEntity = new InputStreamRequestEntity(inputStream, requestBytes.length, "application/json; charset=utf-8");
                    postMethod.setRequestEntity(requestEntity);
                    int code = client.executeMethod(postMethod);
                    System.out.println("请求状态" + code);

                    // 这里因该有判断的，根据请求状态判断请求是否成功，然后根据第三方接口返回的数据格式，解析出我们需要的数据
                    byte[] responseBody = postMethod.getResponseBody();
                    String s = new String(responseBody);
                    System.out.println(s);
                    result = s;
                } catch (Exception e) {
                    System.out.println("发送 POST 请求出现异常！" + e);
                    e.printStackTrace();
                } finally {
                    try {
                        if (out != null) {
                            out.close();
                        }
                        if (in != null) {
                            in.close();
                        }
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                }
                JsonRootBean bean = JSON.parseObject(result, JsonRootBean.class);
                Shop data = bean.getData();
                List<ShopInfo> list = data.getList();
                for (ShopInfo shopInfo : list) {
                    Boolean hasInv = shopInfo.getHasInv();
                    String value = shopInfo.getSloganMap().get("1");
                    if (value.contains("1:1") || value.contains("2:1")) {
                        System.out.println(shopInfo.getName() + ":  " + shopInfo.getId() + "  :" + value + ":" + shopInfo.getHasInv());
                        if (shopInfo.getHasInv()|| true) {
                            dataMap.put(new Long(shopInfo.getId()), shopInfo.getName());
                        }
                    }
                }
            }
        }
        if (dataMap.size() > 0 || CaCheUidUtils.getUid().size() > 0) {
            String messageStr = "";
            for (String value : dataMap.values()) {
                messageStr = messageStr + value + ",";
            }
            Message message = new Message();
            message.setAppToken("AT_X2qDwjcIYzrrsUwi4y4KpP8bSQlZFtK8");
            message.setContentType(Message.CONTENT_TYPE_TEXT);
            message.setContent(messageStr);
            message.setTopicId(9990L);
            message.setUids(CaCheUidUtils.getUid());
            message.setUrl("http://wxpuser.zjiecode.com");
            Result<List<MessageResult>> results = WxPusher.send(message);
            log.info("发生成功");
        } else {
            log.info("暂时无货");
        }
    }

}
